import { defineStore } from 'pinia';

const catering = defineStore('catering', {
  state: () => ({
    storeInfo: null,
    cart: [],
  }),

  getters: {
    cartCount() {
      return this.cart.reduce((total, item) => total + item.quantity, 0);
    },
    cartTotal() {
      return this.cart.reduce((total, item) => total + item.price * item.quantity, 0);
    },
    // 获取购物车中某个商品的数量
    getItemQuantity: (state) => (uniqueId) => {
        const item = state.cart.find(cartItem => cartItem.uniqueId === uniqueId);
        return item ? item.quantity : 0;
    }
  },

  actions: {
    setStore(store) {
      // 规范化并保存门店标识，供订单筛选使用
      console.log('【Catering Store】setStore 接收到的 store:', store);
      
      // 支持传入 null 来清空门店信息
      if (store === null) {
        console.log('【Catering Store】清空门店信息');
        this.storeInfo = null;
        this.cart = [];
        return;
      }
      
      const normalized = { ...store };
      // 兼容不同接口的 id 字段
      normalized.shopId = store.shopId || store.id || store.storeId || '';
      console.log('【Catering Store】规范化后的 shopId:', normalized.shopId);
      this.storeInfo = normalized;
      console.log('【Catering Store】最终 storeInfo:', this.storeInfo);
      // 切换门店时清空购物车
      this.cart = [];
    },

    addToCart(product) {
      const uniqueId = product.id + JSON.stringify(product.selectedSpecs);
      const existingItem = this.cart.find((item) => item.uniqueId === uniqueId);

      if (existingItem) {
        existingItem.quantity++;
      } else {
        this.cart.push({ ...product, uniqueId, quantity: 1 });
      }
    },

    updateQuantity(uniqueId, quantity) {
      const item = this.cart.find((item) => item.uniqueId === uniqueId);
      if (item) {
        if (quantity > 0) {
          item.quantity = quantity;
        } else {
          this.removeFromCart(uniqueId);
        }
      }
    },
    
    removeFromCart(uniqueId) {
        this.cart = this.cart.filter(item => item.uniqueId !== uniqueId);
    },

    clearCart() {
      this.cart = [];
    },
  },
});

export default catering;
